package oop.ex3.nameserver.actions;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

import oop.ex3.messages.FileMessage;
import oop.ex3.messages.MessageInterface;
import oop.ex3.messages.PeerInfoMessage;
import oop.ex3.messages.SimpleMessage;
import oop.ex3.messages.ValidHeaders;
import oop.ex3.messages.exception.InvalidHeaderException;

import oop.ex3.nameserver.NSContext;
import oop.ex3.sockets.ClientSocket;

public class SearchFile extends NsAction {
	
	public SearchFile(NSContext context){
		super(context);
	}

	@Override
	public boolean run(ClientSocket socket, MessageInterface msg) {
		
		if (!_context.containsFile(((FileMessage)msg).getFileName())){
			//TODO what if now someone change it??
			try {
				socket.SendMessage(new SimpleMessage(ValidHeaders.FILENOTFOUND));
			} catch (IOException e){
				return false;
			} catch (InvalidHeaderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} return true;
			//TODO someone can change array here
		} else {
			Set<InetSocketAddress> fms = _context.getFmWithFile(
					((FileMessage)msg).getFileName());
			try {
				for (InetSocketAddress fm : fms){
					socket.SendMessage((new PeerInfoMessage(ValidHeaders.FILEADDRESS, fm)));
				}
				socket.SendMessage(new SimpleMessage(ValidHeaders.ENDLIST));
			} catch (IOException e){
				return false;
			} catch (InvalidHeaderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} return true;
	}

}
